MCU = atmega168

CLK = 20000000UL

PROJECT=aki-usb

TARGET = $(PROJECT).elf
CC = avr-gcc

## programmer opcions
AVRDUDE_PROGRAMMERID=usbasp
AVRDUDE_PORT=/dev/ttyUSB0
AVRDUDE=avrdude

## Options common to compile, link and assembly rules
COMMON = -mmcu=$(MCU) -DF_CPU=$(CLK)

## Compile options common for all C compilation units.
CFLAGS = $(COMMON)
CFLAGS += -Wall -O3 -fsigned-char

## Assembly specific flags
ASMFLAGS = $(COMMON)
ASMFLAGS += -x assembler-with-cpp -Wa,

## Linker flags
LDFLAGS = $(COMMON)
LDFLAGS +=  -Wl,-Map=$(PROJECT).map


## Intel Hex file production flags
HEX_FLASH_FLAGS = -j .text -j .data -R .eeprom


## Include Directories
INCLUDES = -I "."

## Objects that must be built in order to link
OBJECTS = usbdrv.o usbdrvasm.o aki-usb.o font.o

## Objects explicitly added by the user
LINKONLYOBJECTS = 

## Build
all: $(TARGET) $(PROJECT).hex $(PROJECT).lss size

## Compile
usbdrv.o: ./usbdrv/usbdrv.c usbconfig.h
	$(CC) $(INCLUDES) $(CFLAGS) -c  $<

usbdrvasm.o: ./usbdrv/usbdrvasm.S usbconfig.h ./usbdrv/asmcommon.inc ./usbdrv/usbdrvasm*.inc
	$(CC) $(INCLUDES) $(ASMFLAGS) -c  $<

oddebug.o: ./usbdrv/oddebug.c usbconfig.h
	$(CC) $(INCLUDES) $(CFLAGS) -c  $<

aki-usb.o: aki-usb.c font.h etl-font-r-dev.c.inc
	$(CC) $(INCLUDES) $(CFLAGS) -c  $<

font.o: font.c
	$(CC) $(INCLUDES) $(CFLAGS) -c  $<

##Link
$(TARGET): $(OBJECTS)
	 $(CC) $(LDFLAGS) $(OBJECTS) $(LINKONLYOBJECTS) $(LIBDIRS) $(LIBS) -o $(TARGET)

%.hex: $(TARGET)
	avr-objcopy -O ihex $(HEX_FLASH_FLAGS)  $< $@

%.lss: $(TARGET)
	avr-objdump -h -S $< > $@

size: ${TARGET}
#	@echo
#	@avr-size -C --mcu=${MCU} ${TARGET}

akiusb-ctrl: akiusb-ctrl.c
	cc -Wall -o akiusb-ctrl akiusb-ctrl.c -lusb

flash: $(PROJECT).hex
	$(AVRDUDE) -c $(AVRDUDE_PROGRAMMERID) -p $(MCU) \
		-P $(AVRDUDE_PORT) -U flash:w:$(PROJECT).hex

# hope it's OK to put this in a Makefile because it's pretty useful
interactive:
	$(AVRDUDE) -c $(AVRDUDE_PROGRAMMERID) -p $(MCU) \
	  	-P $(AVRDUDE_PORT) -t

## Clean target
.PHONY: clean
clean:
	-rm -rf $(OBJECTS) $(PROJECT).elf \
	     $(PROJECT).hex $(PROJECT).lss $(PROJECT).map
	-rm -rf akiusb-ctrl.o akiusb-ctrl
